package com.example.teadoctor;

import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

//茶信息的具体展示界面
public class Information extends AppCompatActivity {
    private Button btnLike;
    private Button btnFavorite;
    private SharedPreferences sp;
    private Set<String> favoriteNames;
    ImageView imageView;
    TextView textView1,textView2,textView3,textView4;
    String name,image,description,method,storage;
    private Drawable drawable,drawable2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_information);

        //获取上一个页面的茶名
        Intent intent = getIntent();
        final String name = intent.getStringExtra("name");

        // 获取TeaDBHelper对象
        TeaDBHelper dbHelper = new TeaDBHelper(Information.this);
        // 获取SQLiteDatabase对象
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        //根据茶名，找到该茶对应的image、description
        String query = "SELECT * FROM tea_info where name=?";
        Cursor cursor = db.rawQuery(query, new String[]{name});
        if(cursor.moveToNext()) {
            image = cursor.getString(cursor.getColumnIndex("image"));
            description = cursor.getString(cursor.getColumnIndex("description"));
            method = cursor.getString(cursor.getColumnIndex("method"));
            storage = cursor.getString(cursor.getColumnIndex("storage"));
        }

        //获取服务器存储的图片，volley框架
        imageView = findViewById(R.id.tea_image);
        String imageUrl = image;
        ImageRequest imageRequest = new ImageRequest(imageUrl, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap bitmap) {
                imageView.setImageBitmap(bitmap);
                //Toast.makeText(getApplicationContext(), "图片加载成功", Toast.LENGTH_SHORT).show();
            }
        }, 0, 0, ImageView.ScaleType.CENTER_CROP, null, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // 处理网络请求错误
                imageView.setImageResource(R.mipmap.logo);
            }
        });
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(imageRequest);

        //将茶的存储信息、做法写在文本框中中
        textView1 = findViewById(R.id.tea_name);
        textView1.setText(name);
        textView2 = findViewById(R.id.tea_description);
        textView3 = findViewById(R.id.tea_method);
        textView3.setText(method);
        textView4 = findViewById(R.id.tea_storage);
        textView4.setText(storage);

        //要获取的txt文件的URL地址
        String url = description;
        //创建一个StringRequest对象，使用GET方式获取茶的描述信息txt文件内容
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //处理获取到的txt文件内容
                        textView2.setText(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //在此处处理请求错误
                textView2.setText("网络繁忙，请等待");
            }
        }) {
            //指定请求字符编码格式为UTF-8
            @Override
            protected String getParamsEncoding() {
                return "UTF-8";
            }
            // 指定响应字符编码格式为UTF-8
            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String parsed;
                try {
                    parsed = new String(response.data, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    parsed = new String(response.data);
                }
                return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
            }
        };

        //将StringRequest对象添加到RequestQueue中
        requestQueue.add(stringRequest);

        //点赞收藏按键
        btnLike = findViewById(R.id.btn_like);
        btnLike.setText("点赞");
        btnFavorite = findViewById(R.id.btn_favorite);
        sp = getSharedPreferences("favorite", MODE_PRIVATE);

        // 设置收藏按钮的状态
        // 获取已收藏的name数组，若无则创建新数组
        final Set<String> favoriteNames = sp.getStringSet("favoriteNames", new HashSet<String>());
        //获取收藏star图标
        drawable = getResources().getDrawable(R.drawable.ic_star_black_24dp);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        drawable2 = getResources().getDrawable(R.drawable.ic_star_border_black_24dp);
        drawable2.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        // 判断该name是否已经收藏
        if (favoriteNames.contains(name)) {
            btnFavorite.setText("取消收藏");
            btnFavorite.setCompoundDrawables(drawable, null, null, null);
        } else {
            btnFavorite.setText("收藏");
            btnFavorite.setCompoundDrawables(drawable2, null, null, null);
        }

        // 设置点击点赞事件
        btnLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "点赞成功", Toast.LENGTH_SHORT).show();
            }
        });

        // 设置点击收藏事件
        btnFavorite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 收藏操作
                // 判断该name是否已经收藏
                if (favoriteNames.contains(name)) {
                    favoriteNames.remove(name);
                    sp.edit().putStringSet("favoriteNames", favoriteNames).apply();
                    btnFavorite.setText("收藏");
                    btnFavorite.setCompoundDrawables(drawable2, null, null, null);
                    Toast.makeText(getApplicationContext(), "取消收藏成功", Toast.LENGTH_SHORT).show();
                } else {
                    favoriteNames.add(name);
                    sp.edit().putStringSet("favoriteNames", favoriteNames).apply();
                    btnFavorite.setText("取消收藏");
                    btnFavorite.setCompoundDrawables(drawable, null, null, null);
                    Toast.makeText(getApplicationContext(), "收藏成功", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    @Override
    protected void onResume() {
        super.onResume();
        //获取上一个页面的茶名
        Intent intent = getIntent();
        name = intent.getStringExtra("name");
        // 存储该页面的name到SharedPreferences中，包括浏览时间
        sp = getSharedPreferences("BrowsingHistory", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        String[] pages = sp.getString("VisitedPages", "").split(",");
        List<String> pageList = new ArrayList<>(Arrays.asList(pages));
        String currentTime = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.getDefault()).format(new Date());
        String pageWithTime = name + "              " + currentTime;
        pageList.add(pageWithTime);
        String newPages = TextUtils.join(",", pageList);
        editor.putString("VisitedPages", newPages);
        editor.apply();

    }

}
